package controller

import (
	"encoding/json"
	"fmt"
	othersmodel "iptv_server/v3/src/models/others_model"
	"iptv_server/v3/src/settings"
	"iptv_server/v3/src/utils"
	"net/http"
	"path"
	"strconv"
	"strings"

	"github.com/gin-gonic/gin"
)

func handleMoreCate(ctx *gin.Context) bool {
	// r.GET("/tv/category/:id/:pg/:key", handlecategory)
	// r.GET("/tv/detail/:id/:key", handleDetail) // sourcekey
	id := ctx.Param("id")
	reqUrl := ctx.Request.URL.String()

	// fmt.Printf("id: %v\n", id)
	if v, _, ok := cache30min.Get(reqUrl); ok {
		// io.WriteString(ctx.Writer, v)
		ctx.String(200, v)
		return true
	}

	if !strings.HasPrefix(id, "more_") {
		return false
	}

	if id == settings.NewCates_PUSH {
		//pushed
		page := ctx.Param("page")
		if page == "" {
			page = ctx.Param("pg")
		}
		if page == "" {
			page = "1"
		}
		ctx.Redirect(http.StatusTemporaryRedirect, fmt.Sprintf("%s%s", settings.URL_PUSHED_VODID_PREFIX, page))
		return true
	}

	// limit
	for _, more := range settings.NewCates_MORES {
		if id == more {
			_handleMore(ctx, more)
			return true
		}
	}
	return false
}

func _handleMore(ctx *gin.Context, group string) {
	dir := path.Join(settings.Dir_StaticFile, settings.Dir_Videos, group)
	if !utils.IsDir(dir) {
		fmt.Printf("[w] not dir,  dir: %v\n", dir)
		ctx.JSON(200, NotFoundJson)
		return
	}

	var pg, starter, ender int
	var page string
	page = ctx.Param("page")
	if page == "" {
		page = ctx.Param("pg")
	}
	if i, err := strconv.Atoi(page); err == nil {
		pg = max(1, i)
	} else {
		//page 从1开始
		pg = 1
	}
	ender = pg * limit
	starter = ender - limit

	//第一层 排序
	dirs_0 := utils.GetDirs(dir)

	//第二层 video
	dirs_1 := make([]struct {
		Name   string
		Parent string
	}, 0)

	// var dirs []fs.DirEntry
	// for _, d0 := range dirs_0 {
	for i := len(dirs_0) - 1; i >= 0; i-- {
		// 倒序!
		d0 := dirs_0[i]
		parent := path.Join(dir, d0.Name())
		for _, v := range utils.GetDirs(parent) {
			dirs_1 = append(dirs_1, struct {
				Name   string
				Parent string
			}{
				Name:   v.Name(),
				Parent: d0.Name(),
			})
		}
	}

	if starter >= len(dirs_1) {
		ctx.JSON(200, NotFoundJson)
		return
		// dirs = make([]fs.DirEntry, 0)
	}

	if len(dirs_1) < ender {
		ender = len(dirs_1)
	}
	vod_dirs := dirs_1[starter:ender]

	// fileInfosPaged := fileInfos[start:end]
	pageX := othersmodel.OPage{
		List: make([]*othersmodel.ODetail, 0),
	}

	//r.GET("/tv/category/:id/:pg/:key", handlecategory)
	// for _, info := range fileInfosPaged {

	// r.GET("/tv/category/:id/:pg/:key", handlecategory)
	// r.GET("/tv/detail/:id/:key", handleDetail) // sourcekey

	// r.GET("/tv/detail_more/:group/:middle/:name", handleMoreDetail)

	for _, vod := range vod_dirs {
		pic := Get_pic(group, vod.Parent, vod.Name)
		vod_id := fmt.Sprintf("/tv/detail_more/%s/%s/%s", group, vod.Parent, vod.Name)
		detail := &othersmodel.ODetail{
			VodId:         vod_id,
			Name:          vod.Name,
			Pic:           pic,
			Vod_play_from: "HomeVideo",
			// Vod_play_url:  vod_play_url,
			Show: true,
		}

		pageX.List = append(pageX.List, detail)
	}
	if len(pageX.List) == 0 {
		ctx.JSON(200, NotFoundJson)
		return
	}

	pageX.Limit = limit
	pageX.Page = pg // page 从1开始
	pageX.PageCount = len(dirs_1) / limit
	if len(dirs_1)%limit != 0 {
		pageX.PageCount += 1
	}

	{
		bs, err := json.Marshal(pageX)
		if err == nil {
			reqUrl := ctx.Request.URL.String()
			cache30min.Save(reqUrl, string(bs))
			ctx.String(200, string(bs))
		}
	}

}

func Get_pic(group, middle, dir string) string {
	d_url := path.Join(settings.UrlPath_VideoRoot, group, middle, dir)
	return fmt.Sprintf("%s/__poster.jpg", d_url)
}
